import json

from flask import Flask, request, render_template

from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket  # 做语法提示

# user_list = []

user_dict = {}

app = Flask(__name__)
@app.route("/ws/<username>")
def my_ws(username):
	# print(request.environ)
	user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
	user_dict[username] = user_socket
	print(user_dict)
	while 1:
		msg = user_socket.receive() # 等待客户端发送的数据
		u_msg = {"from_user":username,"chat":msg}
		for uname,usocket in user_dict.items(): # type:WebSocket
			usocket.send(json.dumps(u_msg))

		# msg = json.loads(msg)
		# print(msg,type(msg))
		# user_socket.send(json.dumps(msg))

@app.route("/webchat")
def webchat():
	return render_template("public_chat.html")


if __name__ == '__main__':
	# app.run("0.0.0.0",9527)
	server = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler)
	server.serve_forever()
